package com.yunchao.feature.lock.presentation.screen

import android.os.Bundle
import android.view.View
import by.kirich1409.viewbindingdelegate.viewBinding
import com.xuexiang.xui.utils.WidgetUtils
import com.yunchao.feature.base.presentation.ext.setDebouncedClickListener
import com.yunchao.feature.base.presentation.ext.toast
import com.yunchao.feature.lock.R
import com.yunchao.feature.lock.databinding.FragmentLockLogBinding
import com.yunchao.feature.lock.domain.model.LockInfoModel
import com.yunchao.feature.lock.presentation.adapter.LockLogAdapter

internal class LockLogFragment : LockFragment(R.layout.fragment_lock_log) {

    private val binding: FragmentLockLogBinding by viewBinding<FragmentLockLogBinding>()
    private val lockLogAdapter: LockLogAdapter by lazy { LockLogAdapter() }
    private var lockLogCount = 0

    override fun initView(view: View, savedInstanceState: Bundle?) {
        binding.lockLogisticsRecyclerView.apply {
            adapter = lockLogAdapter; WidgetUtils.initRecyclerView(this, 0)
        }

        binding.queryLogButton.setDebouncedClickListener {
            val start = binding.startInput.text.toString().trim()
            val number = binding.numberInput.text.toString().trim()
            if (start.isBlank() || number.isBlank()) {
                toast("请输入开始位置和项数")
                return@setDebouncedClickListener
            }

            if (start.toInt() > lockLogCount) {
                toast("起始位置不能大于日志总数")
                return@setDebouncedClickListener
            }

            lockEPCInfo?.apply {
                viewModel.readLockLog(this, start.toInt(), number.toInt())
            }
        }
    }

    override fun handlePageIdle() {
        binding.lockNumber.setText(com.yunchao.feature.base.R.string.锁号)
        binding.lockEpcContent.setText(com.yunchao.feature.base.R.string.EPC)
        binding.lockLogCount.setText(com.yunchao.feature.base.R.string.日志总数)
    }


    override fun handlePageSuccess(lockInfoModel: LockInfoModel) {
        super.handlePageSuccess(lockInfoModel)

        lockLogCount = lockInfoModel.lockLogCount.takeIf { it > 0 }?.also {
            binding.lockLogCount.text = getString(
                com.yunchao.feature.base.R.string.日志总数STR2,
                it
            )
        } ?: 0

        lockLogAdapter.submitList(lockInfoModel.lockLogList)
        binding.lockNumber.text = getString(
            com.yunchao.feature.base.R.string.锁号STR,
            lockInfoModel.lockEPCInfo.id
        )
        binding.lockEpcContent.text =
            getString(com.yunchao.feature.base.R.string.EPCSTR, lockInfoModel.lockEPCInfo.epc)
    }

    override fun onceScanLock() {
        viewModel.inventoryOnceAndLogCount()
    }
}